<template>
    <div class="f-c-c vh100vh login">
        <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item  prop="account">
        <template #label>
           <div style="color: #fff;">账户名</div>
        </template>

      <el-input v-model="ruleForm.account" />
    </el-form-item>
    <el-form-item prop="password">
        <template #label>
           <div style="color: #fff;">密码</div>
        </template>
      <el-input v-model="ruleForm.password" />
    </el-form-item>
    
    <el-form-item>
      <el-button :loading="loading" type="primary" @click="submitForm(ruleFormRef)">
        登录
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>


    </div>

</template>
    
<script setup lang='ts'>
        import { reactive, ref ,} from 'vue'
  //  import { initialRoutes } from '../router';
import { FormInstance, FormRules,ElMessage } from 'element-plus'
import {useRouter} from 'vue-router';
// import request from '../util/request';
import {loginApi} from "../apis/user.js"
const router=useRouter();
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    account:"",
    password:""
})
const loading=ref(false)

const rules = reactive<FormRules>({
    account: [
    { required: true, message: '请输入正确的名字', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入正确的密码', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  
})

const submitForm = async (formEl: FormInstance | undefined) => {

        loading.value=true
  if (!formEl) return
  await formEl.validate((valid:any, fields:any) => {
    if (valid) {
      console.log('submit!')
      loginApi(ruleForm)
      .then(res=>{
        loading.value=false
        const {token,userInfo,permissions}=res
            localStorage.token=token;
            localStorage.userInfo=JSON.stringify(userInfo)
            localStorage.permissions=JSON.stringify(permissions)
                ElMessage.success("登录成功")
                // initialRoutes()
                router.push("/nav")
                .catch(err => {
                    console.log("err", err);
                    loading.value = false;
                })
        
      })
    } else {
      console.log('error submit!', fields)
      loading.value=false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


</script>
    
<style>
    
</style>